package cn.wolfcode.shop.cloud.web.resolver;

import cn.wolfcode.shop.cloud.anno.UserParam;
import cn.wolfcode.shop.cloud.common.CookieUtils;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by wolfcode-lanxw
 */
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(UserParam.class)
                && parameter.getParameterType().equals(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = CookieUtils.getToken(webRequest.getNativeRequest(HttpServletRequest.class));
        return userService.findByToken(token);
    }
}
